package com.example.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.exception.BusinessException;
import com.example.domain.CultureShoppingCart;
import com.example.mapper.CultureShoppingCartDao;
import com.example.service.CultureShoppingCartService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * (CultureShoppingCart)表服务实现类
 *
 * @author makejava
 * @since 2025-03-29 17:58:46
 */
@Service("cultureShoppingCartService")
public class CultureShoppingCartServiceImpl implements CultureShoppingCartService {
    @Resource
    private CultureShoppingCartDao cultureShoppingCartDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public CultureShoppingCart queryById(Integer id) {
        return this.cultureShoppingCartDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param cultureShoppingCart 筛选条件
     * @param pageRequest         分页对象
     * @return 查询结果
     */
    @Override
    public Page<CultureShoppingCart> queryByPage(CultureShoppingCart cultureShoppingCart, PageRequest pageRequest) {
        long total = this.cultureShoppingCartDao.count(cultureShoppingCart);
        return new PageImpl<>(this.cultureShoppingCartDao.queryAllByLimit(cultureShoppingCart, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param cultureShoppingCart 实例对象
     * @return 实例对象
     */
    @Override
    public CultureShoppingCart insert(CultureShoppingCart cultureShoppingCart) {
        CultureShoppingCart cultureShoppingCart1 = cultureShoppingCartDao.queryCartByUserAndProduct(cultureShoppingCart);
        if (ObjectUtil.isNotEmpty(cultureShoppingCart1)) {
            throw new BusinessException(ResultCodeEnum.SHOPPING_CART_ERROR);
        }
        synchronized (CultureProductServiceImpl.class) {
            cultureShoppingCart.setBatchNo(DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        }
        this.cultureShoppingCartDao.insert(cultureShoppingCart);
        return cultureShoppingCart;
    }

    /**
     * 修改数据
     *
     * @param cultureShoppingCart 实例对象
     * @return 实例对象
     */
    @Override
    public CultureShoppingCart update(CultureShoppingCart cultureShoppingCart) {
        this.cultureShoppingCartDao.update(cultureShoppingCart);
        return this.queryById(cultureShoppingCart.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer productId,Integer userId) {
        return this.cultureShoppingCartDao.deleteById(productId,userId) > 0;
    }
}
